package session

import (
	"GoStreamVideoWebsite/api/dbops"
	"GoStreamVideoWebsite/api/defs"
	"GoStreamVideoWebsite/api/utils"
	"sync"
	"time"
)

var sessionMap *sync.Map

func init() {
	sessionMap = &sync.Map{}

}
func LoadSessionsFromDB() {
	mp, err := dbops.RetrieveAllSession()
	if err != nil {
		return
	}
	//mp.Range()
	sessionMap = mp
}
func GenerateNewSessionID(username string) string {
	id := utils.NewUUID()
	ttl := time.Now().Add(time.Minute * 30).Unix() //30min
	sessionMap.Store(id, &defs.SimpleSession{
		Username: username,
		TTL:      ttl,
	})
	dbops.WriteSession(id, ttl, username)
	return id
}
func IsSessionExpired(sid string) (string, bool) {
	ss, ok := sessionMap.Load(sid)
	if ok {
		ct := time.Now().Unix()
		ss := ss.(*defs.SimpleSession)
		if ss.TTL < ct {
			dbops.DeleteSession(sid)
			sessionMap.Delete(sid)
			return "", true
		}
		return ss.Username, false
	}
	return "", true
}
